import { createApp } from 'vue';

// 创建 Vue 应用实例
const app = createApp({});

// 定义 v-dialogDrag 指令
app.directive('dialogDrag', {
  beforeMount(el) { // Vue 3 中的生命周期钩子改为 beforeMount [ty-reference](23)
    const dialogHeaderEl = el.querySelector('.el-dialog__header');
    const dragDom = el.querySelector('.el-dialog');
    console.log('拖拽');

    if (!dialogHeaderEl || !dragDom) return;

    // 设置样式以支持拖拽
    dialogHeaderEl.style.cssText += ';cursor:move;';
    dragDom.style.cssText += ';position:absolute;'; // 移除 top:0px 因为这可能会影响初始布局

    // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
    const sty = (function() {
      if (window.document.currentStyle) {
        return (dom, attr) => dom.currentStyle[attr];
      } else {
        return (dom, attr) => getComputedStyle(dom, false)[attr];
      }
    })();

    // 鼠标按下事件
    dialogHeaderEl.onmousedown = (e) => {
      const disX = e.clientX - dialogHeaderEl.offsetLeft;
      const disY = e.clientY - dialogHeaderEl.offsetTop;

      let styL = sty(dragDom, 'left');
      let styT = sty(dragDom, 'top');

      if (styL.includes('%')) {
        styL = +document.body.clientWidth * (+styL.replace(/%/g, '') / 100);
        styT = +document.body.clientHeight * (+styT.replace(/%/g, '') / 100);
      } else {
        styL = +styL.replace(/\px/g, '');
        styT = +styT.replace(/\px/g, '');
      }

      document.onmousemove = (e) => {
        const l = e.clientX - disX;
        const t = e.clientY - disY;

        // 边界检测逻辑，确保对话框不会超出屏幕边界
        const screenWidth = document.body.clientWidth;
        const screenHeight = document.documentElement.clientHeight;
        const dragDomWidth = dragDom.offsetWidth;
        const dragDomHeight = dragDom.offsetHeight;

        let left = Math.max(0, Math.min(l + styL, screenWidth - dragDomWidth));
        let top = Math.max(0, Math.min(t + styT, screenHeight - dragDomHeight));

        dragDom.style.left = `${left}px`;
        dragDom.style.top = `${top}px`;
      };

      document.onmouseup = () => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    };
  },
  unmounted(el) { // Vue 3 中新增的生命周期钩子 unmounted
    const dialogHeaderEl = el.querySelector('.el-dialog__header');
    if (dialogHeaderEl) {
      dialogHeaderEl.onmousedown = null; // 清除事件监听器
    }
  }
});